//
//  OAuthViewController.swift
//  CJPWB
//
//  Created by 陈锦彭 on 16/3/15.
//  Copyright © 2016年 chenjinpeng. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController {
     ///webView
    @IBOutlet weak var webView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置导航条上的内容
        setupNavigationBar()
        //加载授权页面
        loadWebViewWithOAuth()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

   

}
// MARK: - 加载数据
extension OAuthViewController {
    //加载授权页面
    private func loadWebViewWithOAuth() {
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        guard let url = NSURL(string: urlStr) else { return}
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        webView.delegate = self
    
    }

}


// MARK: -  设置导航条上的内容
extension OAuthViewController {
    ///设置导航条上的内容
    private func setupNavigationBar() {
        //左边按钮的设置
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "leftBtnClick")
    
        //右边按钮的设置
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target: self, action: "righrBtnClick")
        
        //中间按钮的标题
        navigationItem.title = "登陆页面"
    }
    
}

// MARK: - 设置导航条上的按钮的点击事件
extension OAuthViewController {
    
    @objc private func leftBtnClick() {
     dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss()
    }
    
    @objc private func righrBtnClick() {
        //获取要执行的js(JavaScript)代码
        let jsCode = "document.getElementById('userId').value='peng827@qq.com';document.getElementById('passwd').value='900827chen';"
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }


}


// MARK: - UIWebViewDelegate的代理方法
extension OAuthViewController : UIWebViewDelegate {
    //开始加载页面式调用
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //结束加载页面式调用
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //加载失败时调用
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    
    //是否开始加载请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //1.获取到url
        guard let url = request.URL?.absoluteString else {
            return true
        }
        //2.判断url中有没有code
        if !url.containsString("code="){
            return true
        }
        //3.截取url中的code
        guard let code = url.componentsSeparatedByString("code=").last else{
            return true
        }
        //4.发送网络请求获取access token
        UserAccountViewModel.shareInstance.getAccessToken(code) { (isSuccess) -> () in
            //如果没有获取成功
            if !isSuccess {
            return
            }
            //跳转到欢迎界面
            self.dismissViewControllerAnimated(true, completion: { () -> Void in
                
            })
            UIApplication.sharedApplication().keyWindow?.rootViewController = WelcomeViewController()
        }
        
        return false
    }
    
}